'''
Created on Apr 7, 2011

@author: riche
'''

from ft.framework import component
from ft.apps.gamma.util import small_hash_map
from ft.apps.gamma import constants

class Merge(component.Implementation):
    '''
    classdocs
    '''


    def __init__(self, name, num_streams):
        '''
        Constructor
        '''
        component.Implementation.__init__(self, name)
        for i in range(num_streams):
            self.add_port(component.Port('in%s'%i, 'merge'))
        self.add_port(component.Port('out', '__OUT__'))
        
    def merge(self, msg):
        #print('merging: %s'%msg.strip())
        self.send_out('out', msg)
        
class Split(component.Implementation):
    
    def __init__(self, name, num_streams, key):
        component.Implementation.__init__(self, name)
        for i in range(num_streams):
            self.add_port(component.Port('out%s'%i, '__OUT__'))
        self.add_port(component.Port('in', 'split'))
        self._num_streams = num_streams
        self._key = key        
        
    def split(self, msg):
        if msg != 'DONE':
            tuple = msg.split(':')
            jk = tuple[self._key]
            index = small_hash_map.get_key(constants.SIZE, jk)
            outport = index//(constants.SIZE//self._num_streams)
            #print('%s->%s'%(msg.strip(),outport))
            self.send_out('out%s'%outport, msg)
        else:
            for i in range(self._num_streams):
                self.send_out('out%s'%i, msg)
        
        
        
        